package yja.gzw.app.activity

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import com.kwai.auth.common.KwaiConstants
import com.kwai.opensdk.sdk.model.base.OpenSdkConfig
import com.kwai.opensdk.sdk.model.postshare.PostShareMediaInfo
import com.kwai.opensdk.sdk.model.postshare.SingleVideoPublish
import com.kwai.opensdk.sdk.model.postshare.plc.MiniProgramPlcBindInfo
import com.kwai.opensdk.sdk.openapi.IKwaiOpenAPI
import com.kwai.opensdk.sdk.openapi.KwaiOpenAPI
import yja.gzw.app.FileProviderUtil
import yja.gzw.app.R
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityWodezhanghuaBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import java.io.File


class WodezhanghuaActivity :BaseActivity<Mainviewmodel, ActivityWodezhanghuaBinding>(R.layout.activity_wodezhanghua){
    var albumFile: File? = null
    private val platformList = java.util.ArrayList<String>(2)
    var mKwaiOpenAPI:IKwaiOpenAPI?=null
    var idid=""
    var patjst=""
    override fun onDestroy() {
        super.onDestroy()


        viewmodel.onshangchuandingdanshipingwang(UserData.token, mapOf("order_id" to idid,"video_url" to patjst))

    }

    override fun initView() {
        val ids =intent.getStringExtra("idid")
        val paths =intent.getStringExtra("paths")
        patjst=paths!!
        idid=ids!!
        mKwaiOpenAPI= KwaiOpenAPI(this@WodezhanghuaActivity)
        platformList.add(KwaiConstants.Platform.NEBULA_APP)
        platformList.add(KwaiConstants.Platform.KWAI_APP)


        val openSdkConfig = OpenSdkConfig.Builder()
            .setGoToMargetAppNotInstall(true) // 应用未安装，是否自动跳转应用市场
            .setGoToMargetAppVersionNotSupport(true) // 应用已安装但版本不支持，是否自动跳转应用市场
            .setSetNewTaskFlag(true) // 设置启动功能页面是否使用新的页面栈
            .setSetClearTaskFlag(true) // 设置启动功能页面是否清除当前页面栈，当isSetNewTaskFlag为true时生效
            .setShowDefaultLoading(false) // 是否显示默认的loading页面作为功能启动的过渡
            .build()
        mKwaiOpenAPI?.setOpenSdkConfig(openSdkConfig);

        binding.bangdingzhanghao.setOnClickListener {
            val intnet=Intent(this,BasedingzhanghaoActivity::class.java)
            startActivity(intnet)
        }



       // binding.fabuship.setOnClickListener {
           // albumFile= File("/sdcard/Download/downloaded_video.mp4")
        //todo 目前报空指针
            publishSingleVideo(UserData.files)


        //  }

        binding.fnfnfn.setOnClickListener {

            viewmodel.onshangchuandingdanshipingwang(UserData.token, mapOf("order_id" to ids.toString(),"video_url" to paths!!))


        }


    }

    override fun dataObservese() {

        viewmodel.onshangchuandingdanshiping.observe(this, Observer {
            if(it.code==1){
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
                val intne=Intent(this, ChengjieActivity::class.java)

                startActivity(intne)
                finish()

            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }


        })


    }





    class ShareParam(var albumFile: File, var privateFile: File, var isUserPrivateFile: Boolean)


    // 发布单个视频
    fun publishSingleVideo(param: File) {
        val req = SingleVideoPublish.Req()
        req.sessionId = mKwaiOpenAPI?.openAPISessionId
        req.transaction = "SingleVideoPublish"

        // 设置功能调起快手支持应用，KwaiPlatform.Platform.KWAI_APP（快手主站），KwaiPlatform.Platform.NEBULA_APP（快手极速版）
        // 按数组顺序检查应用安装和版本情况，从中选择满足条件的第一个应用调起，若不设置则默认启动快手主站应用
        req.platformArray = platformList.toTypedArray<String>()
        req.mediaInfo = PostShareMediaInfo()
        val videoFiles = ArrayList<String>()
        var filePath: String = param.absolutePath



        videoFiles.add(filePath)
        req.mediaInfo.mMultiMediaAssets = videoFiles
        printShareFilePath(req.mediaInfo.mMultiMediaAssets)

            req.thirdExtraInfo = ""

        val mediaInfoMap = getMediaMap()
        if (mediaInfoMap != null && !mediaInfoMap.isEmpty()) {
            req.mediaInfo.mMediaInfoMap = mediaInfoMap
        }


        // 发布时挂载小程序PLC，该能力需要申请权限，要求快手和极速版版本不低于11.3.20
        val plcMpAppId: String =""
        val plcTitle: String = ""
        val plcMpPath: String = ""
        if (!TextUtils.isEmpty(plcMpAppId) && !TextUtils.isEmpty(plcTitle) && !TextUtils.isEmpty(
                plcMpPath
            )
        ) {
            req.mPlcBindInfo = MiniProgramPlcBindInfo(plcTitle, plcMpAppId, plcMpPath)
        }

        mKwaiOpenAPI?.sendReq(req,this)
    }


    private fun printShareFilePath(pathList: java.util.ArrayList<String>) {
        for (item in pathList) {
            Log.d("视频发布配置", "path is $item")
        }
    }
    private fun getMediaMap(): Map<String, Any> {
        val mediaMap = HashMap<String, Any>()

        try {
            if (!TextUtils.isEmpty("视频")) {
                val mapValues =
                    "视频".split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                for (result in mapValues) {
                    val resultValues =
                        result.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                    if (resultValues != null && resultValues.size >= 2) {
                        mediaMap[resultValues[0]] = resultValues[1]
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mediaMap
    }

}